package meijuli.com.join51.business.aliyun;

import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static String md5(File file) {
        if (!file.isFile()) {
            return null;
        }

        MessageDigest digest = null;
        FileInputStream inputStream = null;
        byte[] buffer = new byte[1024];
        try {
            digest = MessageDigest.getInstance("MD5");
            inputStream = new FileInputStream(file);

            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
        } catch (NoSuchAlgorithmException | IOException e) {
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        BigInteger bigInteger = new BigInteger(1, digest.digest());
        String md5 = bigInteger.toString(16);

        while(md5.length() < 32 ) {
            md5 = "0" + md5;
        }
        return md5;
    }

    public static boolean checkFileMD5(String fileName, String md5) {
        File file = new File(fileName);
        return file.exists() && !TextUtils.isEmpty(md5) && md5.equals(md5(file));
    }
}